package resource

import (
	"mallgo/internal/common/request"
	"mallgo/internal/common/response"
	modelRequest "mallgo/internal/resources/product/api/domain/request"
	response2 "mallgo/internal/resources/product/api/domain/response"
	"mallgo/internal/resources/product/model"
	"time"

	"gorm.io/gorm"
)

type ProductResource struct {
	db *gorm.DB
}

func NewProductResource(db *gorm.DB) *ProductResource {
	return &ProductResource{db}
}

func (r *ProductResource) Create(product *modelRequest.ProductRequest) *response.ResponseObject {
	tx := r.db.Begin()

	// 创建订单
	m := modelRequest.ConvertModel(product)
	addDate := time.Now()
	m.AddDate = &addDate
	lastDate := time.Now()
	m.LastDate = &lastDate

	if err := tx.Create(&m).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "创建订单失败")
	}
	tx.Commit()
	return response.Success(response2.ConvertResponse(m))
}

func (r *ProductResource) Update(req *modelRequest.ProductRequest) *response.ResponseObject {
	tx := r.db.Begin()
	var m model.Product
	if err := tx.Where("id = ?", req.ID).Find(&m).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "查询订单失败")
	}
	// 更新订单
	m2 := modelRequest.ConvertModel(req)
	lastDate := time.Now()
	m2.LastDate = &lastDate
	if err := tx.Model(&m).Updates(&m2).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "更新订单失败")
	}
	tx.Commit()
	return response.Success("更新数据成功")
}

func (r *ProductResource) Delete(req *modelRequest.ProductRequest) *response.ResponseObject {
	tx := r.db.Begin()

	// 删除订单
	m := modelRequest.ConvertModel(req)
	if err := tx.Delete(&m).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "删除订单失败")
	}
	tx.Commit()
	return response.Success(nil)
}

func (r *ProductResource) Search(request *modelRequest.ProductSearch) *response.PageResponse {
	// 获取分页参数
	page := request.Page
	pageSize := request.Size
	var total int64

	// 查询订单
	var models []model.Product

	// 分页查询
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 {
		pageSize = 10
	}
	offset := (page - 1) * pageSize

	query := r.db.Model(&model.Product{})
	// 添加查询条件
	if request.Note != "" {
		query = query.Where("note LIKE ?", "%"+request.Note+"%")
	}
	if request.Name != "" {
		query = query.Where("name LIKE ?", "%"+request.Name+"%")
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return response.ErrorPage(500, "查询应用总数失败")
	}

	if err := query.Offset(offset).Limit(pageSize).Order("id DESC").Find(&models).Error; err != nil {
		return response.ErrorPage(500, "查询应用失败")
	}

	return response.SuccessPage(models, page, pageSize, total)
}

func (r *ProductResource) View(request *request.ViewRequest) *response.ResponseObject {
	tx := r.db.Begin()

	// 查询订单
	var m model.Product
	if err := tx.Where("id = ?", request.ID).Find(&m).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "查询订单失败")
	}
	tx.Commit()
	return response.Success(response2.ConvertResponse(&m))
}
